package com.shangye.miaoSha.service;

import com.shangye.miaoSha.dao.MiaoshaUserDao;
import com.shangye.miaoSha.domain.MiaoshaUser;
import com.shangye.miaoSha.exception.GlobalException;
import com.shangye.miaoSha.redis.MiaoshaUserKey;
import com.shangye.miaoSha.redis.RedisService;
import com.shangye.miaoSha.result.CodeMsg;
import com.shangye.miaoSha.util.MD5Util;
import com.shangye.miaoSha.util.UUIDUtil;
import com.shangye.miaoSha.vo.LoginVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Service
public class MiaoshaUserService {

    public static final String COOKIE_NAME_TOKEN = "token";

    @Autowired
    MiaoshaUserDao miaoshaUserDao;

    @Autowired
    RedisService redisService;

    public MiaoshaUser getById(long id){
        return miaoshaUserDao.getById(id);
    }

    public boolean login(HttpServletResponse response, LoginVo loginVo){
        if(loginVo == null){
            throw new GlobalException(CodeMsg.SERVER_ERROR);
        }

        String mobile = loginVo.getMobile();
        String formPass = loginVo.getPassword();

        MiaoshaUser miaoshaUser = getById(Long.parseLong(mobile));
        if(miaoshaUser == null){
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }

        String dbPass = miaoshaUser.getPassword();
        String saltDB = miaoshaUser.getSalt();
        String calcPass = MD5Util.formPassToDBPass(formPass, saltDB);
        if(!calcPass.equals(dbPass)){
            throw new GlobalException(CodeMsg.PASSWORD_ERROR);
        }
        String token = UUIDUtil.uuid();
        addCookie(response, token, miaoshaUser);
        return true;
    }

    public MiaoshaUser getByToken(HttpServletResponse response, String token){
        if(StringUtils.isEmpty(token)){
            return null;
        }
        MiaoshaUser miaoshaUser  = redisService.get(MiaoshaUserKey.token, token, MiaoshaUser.class);
        if(miaoshaUser != null){
            addCookie(response, token, miaoshaUser);
        }
        return miaoshaUser;
    }

    private void addCookie(HttpServletResponse response, String token, MiaoshaUser miaoshaUser){
        // 生成cookie

        redisService.set(MiaoshaUserKey.token, token, miaoshaUser);
        Cookie cookie = new Cookie(COOKIE_NAME_TOKEN, token);
        cookie.setMaxAge(MiaoshaUserKey.token.expireSeconds());
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
